<?php

namespace app\modules\search\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\modules\clinical\models\Crtinfo;

class SearchExcel extends Crtinfo
{
    public $pt_name;
    public $ppt_id;//病案号

    public function rules()
    {
        // 只有在 rules() 函数中声明的字段才可以搜索
        return [
            [['crt_time'], 'safe'],
            [['crt_name'], 'string', 'max' => 20],
            [['pt_name', 'ppt_id', 'pt_diagnose'], 'string', 'max' => 30],
        ];
    }

    public function search($params)
    {
        $query = Crtinfo::find()->where(['hspt_crtinfo.delete_at' => 0]);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => [
                    'crt_time' => SORT_DESC,
                ]
            ],
        ]);

        // 从参数的数据中加载过滤条件，并验证
        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        if ($this->ppt_id || $this->pt_name) {//普通搜索
            $query->joinWith(['patient']);
        }

        $this->clearDate(['crt_time']);

        $query->andFilterWhere(['like', 'hspt_patient.pt_id', $this->ppt_id])
              ->andFilterWhere(['like', 'hspt_patient.pt_name', $this->pt_name])
              ->andFilterWhere(['pt_diagnose' => strtolower($this->pt_diagnose)])
              ->andFilterWhere(['=', 'crt_name', $this->crt_name])
              ->andFilterWhere(['like', 'crt_time', $this->crt_time]);

        return $dataProvider;
    }

    protected function clearDate($arr)
    {
        foreach ($arr as $param) {
            $this->$param = preg_replace('/_*(-|:)_*(-|:)_*/', '', $this->$param);
        }
    }
}